package shapewar.engine.model;

import shapewar.conf.Conf;
import shapewar.engine.calc.Pos;
import shapewar.engine.intefac.IHittable;
import shapewar.engine.intefac.Regedit;
import shapewar.engine.model.abst.ModelAdapter;
import shapewar.engine.presenter.Presenter;

public class Protector extends ModelAdapter {
	private float ptr[][] = new float[64][2];
	private Tank father;
	private float t = 0;
	private float round_speed = Conf.protector_round_speed;
	
	public int count = Conf.protector_init_count;
	public float R;
	public Protector(Presenter pst, Tank father) {
		super(pst, father._id, father._x, father._y, Conf.protector_init_round_radium, father._depth);
		this.father = father;
	}

	@Override
	public void init() {
		R = Conf.protector_radium;
		updateRadium();
		pst.bridge.addView(pst.bridge.createProtectorView(this));
		pst.regist(this,Regedit.IRepeat4Protector,Regedit.IView);
	}

	@Override
	public void destory() {
		count = 0;
		pst.bridge.removeView(getView());
		pst.registoff(this,Regedit.IRepeat4Protector,Regedit.IView);
	}
	
	@Override
	public void repeat() {
		for(int i=0;i<count;i++){
			ptr[i][0] = r * (float)Math.cos((1.0*i/count * 360 + t) * Math.PI / 180);
			ptr[i][1] = r * -(float)Math.sin((1.0*i/count * 360 + t) * Math.PI / 180);
		}
		t += round_speed;
		pst.bridge.invalidate(this);
	}
	
	public float[][] getPtr() {
		return ptr;
	}
	
	public void updatePos(){
		_x = father._x;
		_y = father._y;
		pst.bridge.invalidate(this);
	}
	
	@Override
	protected void updateRadium() {
		float d = 1.5f * R;
		float theta = 2 * (float)Math.PI / count;
		r = 0.5f * (float)Math.sqrt(4*d*d/(1-Math.cos(theta))) + Conf.protector_init_round_radium;
	}
	
	public Tank getFather(){
		return father;
	}
	
	public void plus(){
		plus(1);
	}
	
	public void plus(int n){
		if((count+=n)>=ptr.length){
			ptr = new float[count*2][2];
		}
		updateRadium();
	}
	
	public void minus(){
		count--;
		updateRadium();
	}
	
	public boolean hitTest(IHittable blt){
		for(int i=0;i<count;i++){
			Pos tmp = new Pos(_x + ptr[i][0],_y + ptr[i][1]);
			if(calcer.hitTest(blt.getPos(), tmp, blt.getHitableDistance() + R*1.1f)){
				return true;
			}
		}
		return false;
	}
	@Override
	public String toString() {
		return "Protector(x,y = "+pos+"),targetx,target_y = "+target+",rotation = "+_rotation+")";
	}
}
